<template>
  <div id="specTraceRec">
    <Breadcrumb content="条码状态跟踪" />
    <div class="bodyContent">
      <splitpanes class="area">
        <!-- 查询条件 -->
        <pane size="20">
          <div v-loading="Floading">
            <el-scrollbar style="height: 100%">
              <el-form :model="form" label-width="100px">
                <el-row>
                  <el-col :span="23">
                    <el-form-item label="条码号">
                      <el-input ref="specCodeInput" type="text" v-model="form.reqNo" placeholder="请输入条码号" @keyup.enter="keyupEnter" clearable> </el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="23">
                    <el-form-item label="病历号">
                      <el-input type="text" v-model="form.patNo" placeholder="请输入病历号" clearable @keyup.enter="keyupEnter"></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row>
                  <el-col :span="23">
                    <el-form-item label="床号">
                      <el-input type="text" v-model="form.bedNo" placeholder="请输入床号" clearable @keyup.enter="keyupEnter"></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row>
                  <el-col :span="23">
                    <el-form-item label="姓名">
                      <el-input type="text" v-model="form.patNa" placeholder="请输入姓名" clearable @keyup.enter="keyupEnter"></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row>
                  <el-col :span="23">
                    <el-form-item prop="reqDeptNa" label="科室">
                      <SelectDataList ref="employeeSelectRef" :url="'/api/sys/getDepartmentList'" :displayField="[{ title: '科室编码', props: 'code' }, { title: '科室名称', props: 'name' }]" :title="'点击选择科室'" :searchParam="{ orgId: orgId }" @selectDataRow="SelectRowDeptClick" :inputWidth="'100%'" v-model="form.reqDeptName" :placeholder="'选择科室'" @clearValue="clearDeptName" />
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row>
                  <el-col :span="23">
                    <el-form-item label="病人类型" prop="patTypeName">
                      <SelectDataList ref="employeeSelectRef" :url="'/api/sys/basDictDetail/findDictDetailList'" :displayField="[{ title: '编码', props: 'code' }, { title: '名称', props: 'name' }]" :title="'点击选择病人来源'" :searchParam="{ code: 'PATTYPE' }" @selectDataRow="SelectRowClick" :inputWidth="'100%'" v-model="form.patTypeName" :placeholder="'选择病人来源'" @clearValue="clearPatTypeName" />
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row>
                  <el-col :span="23">
                    <el-form-item label="开始日期">
                      <el-date-picker v-model="form.startTime" type="datetime" placeholder="选择开始时间" align="right" value-format="YYYY-MM-DD HH:mm:ss" style="width: 100%" :shortcuts="shortcuts"></el-date-picker>
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row>
                  <el-col :span="23">
                    <el-form-item label="结束日期">
                      <el-date-picker v-model="form.endTime" type="datetime" placeholder="选择结束时间" align="right" value-format="YYYY-MM-DD HH:mm:ss" style="width:100%" :shortcuts="shortcuts"></el-date-picker>
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row>
                  <el-col :span="23">
                    <el-form-item label="TAT节点">
                      <VxePulldownSelectionWithNa style="width: 100%" :url="'/api/lab-tat-node/findLabTatNodeList'" @confirmClick="confirmSelection" :tableColumn="[
                          { type: 'seq', title: '#', width: '30px' },
                          { field: 'tatNodeNo', title: '编码' },
                          { field: 'tatNodeNa', title: '名称' }
                        ]" :aimKeys="[
  { aimKey: 'tatNodeNo', rowKey: 'tatNodeNo' },
  { aimKey: 'tatNodeNa', rowKey: 'tatNodeNa' }
]" :displayTexts="['tatNodeNa']" :displayTextObj="form.tatNodeNa ? form.tatNodeNa : ''" />
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row>
                  <el-col :span="23">
                    <el-form-item label="范围">
                      <el-radio-group v-model="form.range" size="small">
                        <el-radio-button label="1" :value="'1'">全部</el-radio-button>
                        <el-radio-button label="2" :value="'2'">仅超期</el-radio-button>
                        <el-radio-button label="3" :value="'3'">无超期</el-radio-button>
                      </el-radio-group>
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row>
                  <el-col :span="23">
                    <el-form-item>
                      <el-button type="primary" plain @click="handleSearch()">查询</el-button>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
            </el-scrollbar>
          </div>
        </pane>
        <pane size="80">
          <splitpanes horizontal>
            <pane size="45">
              <vxe-toolbar>
                <template #buttons>
                  <span class="text-blue vxe-icon-success-circle-fill"></span>
                  <span class="margin-lr-xs">正常</span>
                  <span class="text-red vxe-icon-warning-triangle-fill"></span>
                  <span class="margin-lr-xs">异常</span>
                </template>
              </vxe-toolbar>
              <div class="tableBox">
                <vxe-grid ref="supplierTableRef" v-bind="gridOptions" :row-config="{ isCurrent: true }" :loading="Sloading" @current-change="supplierRowClick">
                  <template #dync_default="{ row, column }">
                    <span v-if="row[column.field]" class="text-red vxe-icon-warning-triangle-fill">
                      <span class="margin-left-xs"></span>
                    </span>
                    <span v-else class="text-blue vxe-icon-success-circle-fill"></span>
                  </template>
                  <template #sex_default="{ row }">
                    <span> {{ row.sex === '1' ? '男' : row.sex === '2' ? '女' : '未知' }}</span>
                  </template>
                </vxe-grid>
              </div>
            </pane>

            <pane size="55">
              <el-tabs v-model="activeName" type="card" class="demo-tabs" @tab-click="handleClick">
                <el-tab-pane label="流程信息" name="first">
                  <el-scrollbar style="height:calc(100% - 21px);">
                    <div class="padding">
                      <el-card class="shadow padding-tb" v-if="stepList.length > 0">
                        <div class="timelineBox">
                          <TimeLineCompV1 :items="stepList" direction="horizontal" :isShowContent="false" />
                        </div>
                      </el-card>
                    </div>
                  </el-scrollbar>
                </el-tab-pane>
                <el-tab-pane label="闭环信息" name="second">
                  <el-scrollbar style="height:calc(100% - 21px);">
                    <div class="padding">
                      <el-card class="shadow padding-tb" v-if="closedLoopList.length > 0">
                        <div class="timelineBox">
                          <TimeLineCompV1 :items="closedLoopList" direction="horizontal" :isShowContent="false" />
                        </div>
                      </el-card>
                    </div>
                  </el-scrollbar>
                </el-tab-pane>
                <el-tab-pane label="TAT信息" name="third">
                  <el-scrollbar style="height:calc(100% - 21px);">
                    <div class="padding">
                      <el-card class="shadow padding-tb" v-if="tatNodeList.length > 0">
                        <div class="timelineBox">
                          <TimeLineCompV1 :items="tatNodeList" direction="horizontal" />
                        </div>
                      </el-card>
                    </div>
                  </el-scrollbar>
                </el-tab-pane>
              </el-tabs>
            </pane>
          </splitpanes>
        </pane>
      </splitpanes>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { getCurrentInstance, ref, reactive, onMounted } from 'vue';
import { AppStore } from '../../../stores/store';
import Breadcrumb from '@/components/Breadcrumb.vue';
import { Splitpanes, Pane } from 'splitpanes';
import { IsEmpty, DateToString, formatDateTime } from '@/utils/common';
import SelectDataCheckedList from '@/components/SelectMultDataGrid.vue';
import SelectDataList from '@/components/SelectDataList.vue';
import { VXETable } from 'vxe-table';
import VxePulldownSelectionWithNa from '@/components/VxePulldownSelectionWithNa.vue';
import TimeLineCompV1 from '@/components/TimeLineCompV1.vue';

let testArr = reactive([1, 2, 3])
let store = AppStore();
let { proxy }: any = getCurrentInstance();
let Floading = ref(false); //查询form表单
let Sloading = ref(false); //标本列表
let Tloading = false; //跟踪记录
let Oloading = ref(false); //操作记录
let Rloading = ref(false); //检测结果
let specList: any[] = reactive([]); //标本列表
let traceRecList = []; //跟踪记录
let stepList = reactive([]); //跟踪记录对象
let gridOptions = reactive({
  border: 'inner',
  height: 'auto',
  align: 'left',
  showHeaderOverflow: true,
  showOverflow: true,
  columnConfig: {
    resizable: true
  },
  columns: [],
  data: []
});
let activeName = ref('first');/** */
let closedLoopList = reactive([]);/**闭环节点信息列表 */
let tatNodeList = reactive([]);/**tat接待你信息列表 */
let pickerOpts = ref({
  shortcuts: [
    {
      text: '今天',
      onClick(picker) {
        picker.$emit('pick', new Date());
      }
    },
    {
      text: '昨天',
      onClick(picker) {
        const date = new Date();
        date.setTime(date.getTime() - 3600 * 1000 * 24);
        picker.$emit('pick', date);
      }
    },
    {
      text: '一周前',
      onClick(picker) {
        const date = new Date();
        date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
        picker.$emit('pick', date);
      }
    }
  ]
});
const PageSizeList = [10, 50, 100, 200, 500];
let page = reactive({
  currentPage: 1,
  pageSize: PageSizeList[1],
  totalResult: 0
});
let form = ref({
  id: null, //标本id
  reqNo: '',
  patNo: '', //病历号
  bedNo: '', // 床号
  patNa: '',
  reqDept: '',
  reqDeptName: '',
  reqDeptNa: '',
  patType: '', //病人类型
  patTypeName: '',
  startTime: formatDateTime(new Date(), 'yyyy-MM-dd 00:00:00'),
  endTime: formatDateTime(new Date(), 'yyyy-MM-dd 23:59:59'), //申请开始时间、结束时间
  pageIndex: page.currentPage,
  pageSize: page.pageSize,
  range: '1',/**查询范围1，全部  2，仅超期 3，仅无超期 */
  tatNodeNa: '',
  tatNodeNo: ''
});
let orgId = ref('');
const shortcuts = [
  {
    text: '今天',
    value: new Date(),
  },
  {
    text: '昨天',
    value: () => {
      const date = new Date()
      date.setDate(date.getDate() - 1)
      return date
    },
  },
  {
    text: '一周前',
    value: () => {
      const date = new Date()
      date.setDate(date.getDate() - 7)
      return date
    },
  },
]
// 页面加载时更新报告单元/字典
onMounted(() => {
  orgId.value = store.userInfo.orgId;
  //getSpecList();
});
// 停用的行 红色背景高亮
const rowStyle = ({ row, rowIndex }) => {
  if (row.isStop) {
    return {
      backgroundColor: '#ffd5d5',
      color: 'red'
    };
  }
};
// 条数/页

//点击每页数量
function handleSizeChange({ type, currentPage, pageSize }) {
  if (type === 'size') {
    page.currentPage = 1;
  } else {
    page.currentPage = currentPage;
  }
  page.pageSize = pageSize;
  getSpecList();
}

// 日期选择事件
// function timeSelectChange() {
//   handleSearch();
// }
function keyupEnter(e: any) {
  getSpecList();
}
// 查询
function handleSearch() {
  getSpecList();
}

// 查询标本信息列表
function getSpecList() {
  Sloading.value = true;
  specList.length = 0;
  gridOptions.columns.length = 0;
  gridOptions.data.length = 0;
  const url = '/lab/reqMain/findLabTatReqMainList';
  proxy.$http
    .get(url, { params: form.value })
    .then((res: any) => {
      Sloading.value = false;
      const columnStr = JSON.stringify(res.data.columns);
      let columnStr1 = columnStr.replaceAll('default_', 'default');
      let columnStr2 = JSON.parse(columnStr1);
      Object.assign(gridOptions.columns, columnStr2);
      Object.assign(gridOptions.data, res.data.labReqMains);
      if (gridOptions.data && gridOptions.data.length > 0) {
        supplierTableRef.value?.setCurrentRow();
      }
    })
    .catch((err: any) => {
      Sloading.value = false;
    });
}
// 行点击事件
function supplierRowClick({ row, rowIndex }: any) {
  (proxy.$refs.supplierTableRef as any).setCurrentRow(row);
  getTraceRecList({ row });
  findLabReqMainClosedLoopInfo({ row });
  findLabReqMainTatInfo({ row });
}


/**加载闭环展示 */
function findLabReqMainClosedLoopInfo({ row }) {
  closedLoopList.length = 0;
  console.log('====================');
  
  const url = '/lab/mainState/getTraceRecTwoList';
  proxy.$http
    //注意此处的数据条数
    .get(url, {
      params: { reqNo: row.reqNo, isCloopShow: true }
    })
    .then((res: any) => {

      res.data.forEach(e => {
        const m = { title: e.stateName, timestamp: e.operateTime, acter: e.operator, content: e.remark };
        closedLoopList.push(m);
      });
    })
    .catch((err: any) => {
      proxy.$alert('获取流程节点失败', '提示');
    });
  // closedLoopList.length = 0;
  // const url = '/lab/reqMain/findLabReqMainClosedLoopInfo';
  // proxy.$http
  //   //注意此处的数据条数
  //   .get(url, {
  //     params: { id: row.id, reqNo: row.reqNo }
  //   })
  //   .then((res: any) => {
  //     res.data.forEach(e => {
  //       e.acter = '管理员';
  //     });
  //     Object.assign(closedLoopList, res.data);
  //   })
  //   .catch((err: any) => {
  //     proxy.$alert('获取流程节点失败', '提示');
  //   });
}
/**加载TAT 节点展示 */
function findLabReqMainTatInfo({ row }) {
  const url = '/lab/reqMain/findLabReqMainTatInfo';
  proxy.$http
    //注意此处的数据条数
    .get(url, {
      params: { id: row.id, reqNo: row.reqNo }
    })
    .then((res: any) => {
      tatNodeList.length = 0;
      Object.assign(tatNodeList, res.data);
    })
    .catch((err: any) => {
      proxy.$alert('获取流程节点失败', '提示');
    });
}
// 获取跟踪记录
function getTraceRecList({ row }) {
  stepList.length = 0;
  // operationList.length = 0;

  Tloading = true;
  const url = '/lab/mainState/getTraceRecTwoList';
  proxy.$http
    //注意此处的数据条数
    .get(url, {
      params: { id: row.id, reqNo: row.reqNo }
    })
    .then((res: any) => {
      Tloading = false;
      res.data.forEach(e => {
        const m = { title: e.stateName, timestamp: e.operateTime, acter: e.operator, content: e.remark };
        stepList.push(m);
      });
    })
    .catch((err: any) => {
      Tloading = false;
      proxy.$alert('获取流程节点失败', '提示');
    });
}
function clearDeptName() {
  form.value.reqDept = '';
  form.value.reqDeptName = '';
}
function clearPatTypeName() {
  form.value.patType = '';
  form.value.patTypeName = '';
}
function SelectRowDeptClick(e: any) {
  form.value.reqDept = e.code;
  form.value.reqDeptName = e.name;
}
function SelectRowClick(e: any) {
  form.value.patType = e.code;
  form.value.patTypeName = e.name;
}
/**下拉选择确定事件 */
function confirmSelection(e) {
  e.aimKeys.forEach((r) => {
    form[r.aimKey] = e.row[r.rowKey];
  });
}
let enterIndex = 0;
//确定选择
function ConfirmByClick(row, name) {
  if (!IsEmpty(name)) {
    form[name + 'Id'] = row.id;
    form[name + 'Name'] = row.name;
  }

  const ele: any = proxy.$refs[name + 'InputElemt'];
  ele.focus();
  proxy.$refs['visibleBy' + name] = false;
}

// 输入框点击叉号清除
function clearValue(name) {
  form[name + 'Id'] = null;
  form[name + 'Name'] = '';
}
</script>

<style lang="scss" scoped>
#specTraceRec {
  height: 100%;

  .bodyContent {
    height: calc(100% - 60px);

    .area {
      background-color: $base-white;

      .el-form {
        padding-top: 15px;
      }

      .tableBox {
        height: calc(100% - 32px);
      }

      .el-card {
        width: calc(100% - 10px);
        height: 100%;
        border: none;

        :deep(.el-card__body) {
          padding: 5px 10px 0 10px;
          width: calc(100% - 20px);
          height: calc(100% - 5px);
        }
      }

      .el-tabs {
        height: 100%;
        border: none;

        :deep(.el-tabs__content) {
          height: calc(100% - 39px);
          padding: 0;

          .el-tab-pane {
            height: 100%;
          }
        }

        .el-table {
          th,
          td {
            padding: 2px;
          }
        }

        .el-table {
          :deep(.el-table__inner-wrapper) {
            height: 100% !important;
          }
        }
      }
    }
  }
}

/* 设置时间轴为横向排列且自动换行 */
.timeline-wrap {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  /* 自动换行 */
  gap: 16px;
  /* 控制项之间的间距 */
}

.timeline-wrap .el-timeline-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  position: relative;
  width: 200px;
  /* 每个项目的宽度 */
}

.timeline-wrap .el-timeline-item__tail {
  width: 100%;
  /* 横向的连接线 */
  height: 2px;
  margin: 8px 0;
  background-color: #ccc;
  position: relative;
}

.timeline-wrap .el-timeline-item.has-next .el-timeline-item__tail::after {
  content: '➔';
  /* 使用 Unicode 箭头 */
  font-size: 16px;
  color: #ccc;
  position: absolute;
  right: -12px;
  /* 调整箭头位置 */
  top: -6px;
  /* 调整箭头的垂直位置 */
}
</style>
